package org.example.fastproject.core.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.example.fastproject.core.exception.Asserts;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @Author 王海舟
 * @Date 2023/2/1 11:23
 * @PackageName:org.example.fastproject.core.utils
 * @ClassName: FileUtil
 * @Description: 文件工具类
 * @Version 1.0
 */
public class FileUtil {
    public static String rootDir = System.getProperty("user.dir")+"/local/";
    public static String publicDir = System.getProperty("user.dir")+"/local/public/";

    /**
     * 上传文件
     * @param multipartFile
     * @param isPublic
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile multipartFile,boolean isPublic) throws IOException {
        String realName = multipartFile.getOriginalFilename();
        String name = getName(realName);
        File file = null;
        if(isPublic)
            file = new File(publicDir+name);
        else
            file = new File(rootDir+name);
        multipartFile.transferTo(file);
        return name;
    }

    /**
     * 生成随机文件名
     * @return
     */
    public static String getName(String realName){
        String suffix = cn.hutool.core.io.FileUtil.getSuffix(realName);
        String name = IdUtil.fastSimpleUUID();
        if(StrUtil.isNotEmpty(suffix))
            return name+"."+suffix;
        return name;
    }

    /**
     * 获取文件后缀
     * @param realName
     * @return
     */
    public static String getSuffix(String realName){
        return cn.hutool.core.io.FileUtil.getSuffix(realName);
    }

    /**
     * 下载文件
     * @param name
     * @param response
     */
    public static void download(String name, HttpServletResponse response) throws IOException {
        File file = new File(rootDir+name);
        if(!file.exists())
            Asserts.fail("文件丢失");
        // 读到流中
        InputStream inputStream = new FileInputStream(file);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(name, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
